/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sigl.updater.parsers;

import sigl.updater.parsers.WebPage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 *
 * @author uxmal
 */
public class WebParser {

    String moduleName = "", testBaseURL = "http://search.cpan.org/dist/";
    String passed = "", failed = "";
    Pattern mask = Pattern.compile("^(PASS|FAIL) \\(([0-9]+)\\).*$", Pattern.CASE_INSENSITIVE);

    public WebParser(String moduleName) {
        this.moduleName = moduleName;

        parseData();
    }

    private void parseData() {

        String page = "";
        try {
            page = downloadPage(testBaseURL + moduleName);
        } catch (MalformedURLException urlError) {
            System.out.println(urlError);
            return;
        } catch (IOException other) {
            System.out.println(other);
            return;
        }

        StringReader stringReader = new StringReader(page);
        BufferedReader bufReader = new BufferedReader(stringReader);
        String line;

        try {
            while ((line = bufReader.readLine()) != null) {

                Matcher m = mask.matcher(line);
                if ((m.matches()) && (m.groupCount() > 1)) {
                 
                    if (m.group(1).equals("FAIL")) {
                        failed = m.group(2);
                
                    } else if (m.group(1).equals("PASS")) {
                        passed = m.group(2);
            
                    }
                }
            }
            bufReader.close();
        } catch (PatternSyntaxException pse) {/* regex correcte */
        } catch (IOException exc) {
            System.out.println("Erreur de lecture !");
        }

    }

    public String getPassed() {
        return passed;
    }
    public String getFailed() {
        return failed;
    }

    private String downloadPage(String url)
            throws java.net.MalformedURLException, java.io.IOException {

        WebPage file = new WebPage(url);
        String type = file.getMIMEType();
        Object data = file.getContent();

        if (type.equals("text/html") && data instanceof String) {
            return (String) data;
        }

        return null;

    }
}
